#include "Protocol.hpp"
// #include "Socket.hpp"
#include <memory>
#include "TcpServer.hpp"
#include "Calculate.hpp"
#include "Daemon.hpp"
std::string HandlerRequset(std::string& instream, bool* error_code)
{
    *error_code = true;
    Calculate calculate;

    Factory factory; //为什么老师对工厂做一个智能指针呢，factory里面没成员变量啊
    std::shared_ptr<Request> req = factory.BuildRequest();
    std::string message;
    std::string total_package;
    //解package
        // std::cout << "message" << std::endl; //DEBUG

    while(DeCode(instream, &message))
    {
        //将1 + 2 设置进req指向的对象中
        std::cout << message << std::endl; //DEBUG  //原来是没保存啊，难怪，明明注释掉了cout为什么还有打印，没保存
        if(!req->DeSerialize(message)) 
        {
            *error_code = false;
            return "";
        }
        // 有数据了，开始计算，将计算结果设置进 resp指向的对象中
        std::shared_ptr<Response> resp = calculate.Cal(req);
        //序列化
        std::string s_send;
        resp->Serialize(&s_send);
        //添加len \n
        s_send = EnCode(s_send);
        //最后要发送的数据
        total_package += s_send;
    }
    return total_package;
}
int main(int argc, char* argv[])
{
    uint16_t port = std::stoi(argv[1]);

    // Socket* listensockfd = new TcpSocket();
    // listensockfd->BuildListenSocket(port, backlog);
    // while(true)
    // {
    //     std::string peerip;
    //     uint16_t peerport;
    //     Socket* newsockfd = listensockfd->AcceptConnection(&peerip, &peerport);
    //     std::cout << "新链接: sockfd: " << newsockfd->GetSockfd() <<
    //         " client: " << peerip << ":" << peerport << std::endl;
    //     newsockfd->CloseSockfd();
    // }
    Daemon(false, false);
    // std::unique_ptr<TcpServer> svr = std::make_unique(new TcpServer(port));
    std::unique_ptr<TcpServer> tsvr = std::make_unique<TcpServer>(port, HandlerRequset);
    
    tsvr->loop();
}